<template>
  <div class="home-container">
    <!-- 顶部轮播图 -->
    <div class="banner-section">
      <el-carousel :interval="4000" type="card" height="300px">
        <el-carousel-item v-for="(item, index) in bannerList" :key="index">
          <div class="banner-item" :style="{ backgroundImage: `url(${getFullImageUrl(item.imageUrl)})` }">
            <div class="banner-content">
              <h2>{{ item.title }}</h2>
              <p>{{ item.description }}</p>
              <el-button type="primary" @click="navigateTo(item.link)">{{ item.buttonText }}</el-button>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 分类导航 -->
    <div class="category-section">
      <h2 class="section-title">美食分类</h2>
      <div class="category-list">
        <div v-for="category in categories" :key="category.id" class="category-item" @click="filterByCategory(category.id)">
          <div class="category-icon">
            <img :src="getFullImageUrl(category.image)" :alt="category.name">
          </div>
          <div class="category-name">{{ category.name }}</div>
        </div>
      </div>
    </div>

    <!-- 特色菜品 -->
    <div class="featured-section">
      <h2 class="section-title">特色菜品</h2>
      <div class="featured-list">
        <div v-for="dish in featuredDishes" :key="dish.id" class="featured-item" @click="viewDishDetail(dish)">
          <div class="featured-image">
            <img :src="getFullImageUrl(dish.image)" :alt="dish.name">
            <div class="featured-tag" v-if="dish.isNew">新品</div>
          </div>
          <div class="featured-tag sold-out" v-if="dish.status === 0">已售罄</div>
          <div class="featured-info">
            <h3 class="featured-name">{{ dish.name }}</h3>
            <p class="featured-desc">{{ dish.description }}</p>
            <div class="featured-price-row">
              <span class="featured-price">¥{{ dish.price }}</span>
              <el-button type="primary" size="small" @click.stop="addToCart(dish)">
                <i class="el-icon-shopping-cart-2"></i>
                加入购物车
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 热门套餐 -->
    <div class="setmeal-section">
      <h2 class="section-title">热门套餐</h2>
      <div class="setmeal-list">
        <el-card v-for="setmeal in popularSetmeals" :key="setmeal.id" class="setmeal-card" @click="viewSetmealDetail(setmeal)">
          <div class="setmeal-image">
            <img :src="getFullImageUrl(setmeal.image)" :alt="setmeal.name">
            <div class="setmeal-tag sold-out" v-if="setmeal.status === 0">已售罄</div>
          </div>
          <div class="setmeal-info">
            <h3 class="setmeal-name">{{ setmeal.name }}</h3>
            <p class="setmeal-desc">{{ setmeal.description }}</p>
            <div class="setmeal-price-row">
              <span class="setmeal-price">¥{{ setmeal.price }}</span>
              <span class="setmeal-original-price" v-if="setmeal.originalPrice">¥{{ setmeal.originalPrice }}</span>
            </div>
            <el-button type="danger" size="small" @click.stop="addToCart(setmeal)">立即购买</el-button>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 用户评价 -->
    <div class="review-section">
      <h2 class="section-title">顾客评价</h2>
      <el-carousel :interval="5000" arrow="always" height="200px">
        <el-carousel-item v-for="(review, index) in customerReviews" :key="index">
          <div class="review-item">
            <div class="review-avatar">
              <img :src="review.avatar" :alt="review.name">
            </div>
            <div class="review-content">
              <div class="review-rating">
                <el-rate v-model="review.rating" disabled show-score text-color="#ff9900"></el-rate>
              </div>
              <div class="review-text">"{{ review.comment }}"</div>
              <div class="review-author">— {{ review.name }}</div>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 关于我们 -->
    <div class="about-section">
      <h2 class="section-title">关于我们</h2>
      <div class="about-content">
        <div class="about-image">
          <img src="@/assets/images/restaurant.jpg" alt="餐厅环境">
        </div>
        <div class="about-text">
          <h3>食尚先锋</h3>
          <p>我们致力于为您提供最优质的美食体验，每一道菜品都凝聚了厨师的匠心与创意。新鲜的食材、精湛的烹饪技艺，让您在家也能享受到餐厅级别的美味。</p>
          <p>无论是家庭聚餐、朋友聚会还是独自享用，我们都希望通过美食为您的生活增添一份愉悦与满足。</p>
          <el-button type="info" @click="$router.push('/home/products')">浏览全部菜品</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { fileViewPath } from '@/utils/file';
import { getAllCategory } from '@/api/category';
import { getDishList } from '@/api/dish';
import { getSetMealList  } from '@/api/setmeal';
import { addFoodToCart } from '@/api/cart';

const router = useRouter();

// 轮播图数据
const bannerList = ref([
  {
    imageUrl: '2025/04/21/da40258d-4151-4706-ae3f-f65f21052a29-photo-1563379926898-05f4575a45d8.jpg',
    title: '招牌麻辣香锅',
    description: '精选食材，秘制调料，麻辣鲜香，回味无穷',
    buttonText: '立即点餐',
    link: '/home/products'
  },
  {
    imageUrl: '2025/04/21/3efa54b7-2830-4a69-8e99-a6efdb6dcecd-photo-1546964124-0cce460f38ef.jpg',
    title: '限时优惠',
    description: '澳洲进口牛肉，搭配黑椒汁，鲜嫩多汁',
    buttonText: '查看详情',
    link: '/home/products'
  },
  {
    imageUrl: '2025/04/21/5b996efb-9201-4ded-b77a-ad0407d3a9bc-photo-1551183053-bf91a1d81141.jpg',
    title: '新品上市',
    description: '进口松露，奶油芝士，口感丰富，香气四溢',
    buttonText: '了解更多',
    link: '/home/products'
  }
]);

// 分类数据
const categories = ref([]);

// 特色菜品
const featuredDishes = ref([]);

// 热门套餐
const popularSetmeals = ref([]);

// 顾客评价
const customerReviews = ref([
  {
    name: '张先生',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    rating: 5,
    comment: '菜品非常新鲜，口味独特，配送速度也很快，下次还会再来！'
  },
  {
    name: '李女士',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    rating: 4.5,
    comment: '套餐很实惠，分量足够，一家人吃得很满意。'
  },
  {
    name: '王先生',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    rating: 5,
    comment: '服务态度很好，菜品包装精美，味道也很赞！'
  }
]);

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await getAllCategory();
    if (res.code === '200') {
      categories.value = res.data || [];
    }
  } catch (error) {
    console.error('获取分类失败:', error);
  }
};

// 获取特色菜品
const fetchFeaturedDishes = async () => {
  try {
    const res = await getDishList({ pageSize: 100 });
    if (res.code === '200') {
      // 取出特色菜品
      const availableDishes = (res.data.records || []).filter(dish => dish.sort === 1);
      featuredDishes.value = availableDishes.slice(0, 6).map(dish => ({
        ...dish,
        isNew: Math.random() > 0.7, // 随机标记一些为新品
        description: dish.description || '精选食材，匠心烹饪，让您回味无穷'
      }));
    }
  } catch (error) {
    console.error('获取特色菜品失败:', error);
  }
};

// 获取热门套餐
const fetchPopularSetmeals = async () => {
  try {
    const res = await getSetMealList({ pageSize: 100 });
    if (res.code === '200') {
      popularSetmeals.value = (res.data.records || []).slice(0,3).map(setmeal => ({
        ...setmeal,
        description: setmeal.description || '精心搭配，物超所值',
        originalPrice: setmeal.price * 1.2 // 模拟原价
      }));
    }
  } catch (error) {
    console.error('获取热门套餐失败:', error);
  }
};

// 根据分类筛选
const filterByCategory = (categoryId) => {
  router.push({
    path: '/home/products',
    query: { categoryId }
  });
};

// 查看菜品详情
const viewDishDetail = (dish) => {
  // 这里可以实现查看菜品详情的逻辑
  ElMessage.info(`查看菜品: ${dish.name}`);
};

// 查看套餐详情
const viewSetmealDetail = (setmeal) => {
  // 这里可以实现查看套餐详情的逻辑
  ElMessage.info(`查看套餐: ${setmeal.name}`);
};

// 添加到购物车
const addToCart = async (item) => {
  try {

    // 判断菜品是否售罄
    if (item.status === 0) {
      ElMessage.warning('该商品已售罄，无法添加到购物车');
      return;
    }

    const cartItem = {
      name: item.name,
      image: item.image,
      amount: item.price
    };
    
    if (item.categoryId) {
      // 菜品
      cartItem.dishId = item.id;
    } else {
      // 套餐
      cartItem.setmealId = item.id;
    }
    
    const res = await addFoodToCart(cartItem);
    if (res.code === '200') {
      ElMessage.success('已加入购物车');
    } else {
      ElMessage.error(res.msg || '添加失败');
    }
  } catch (error) {
    console.error('添加购物车失败:', error);
    ElMessage.error('添加购物车失败');
  }
};

// 导航到指定链接
const navigateTo = (link) => {
  router.push(link);
};

// 获取图片完整URL
const getFullImageUrl = (imagePath) => {
  if (!imagePath) return '';
  return `${fileViewPath}${formatImagePath(imagePath)}`;
};

// 格式化图片路径
const formatImagePath = (path) => {
  if (!path) return '';
  return path.replace(/\\/g, '/');
};

onMounted(() => {
  fetchCategories();
  fetchFeaturedDishes();
  fetchPopularSetmeals();
});
</script>

<style scoped>
.home-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 轮播图样式 */
.banner-section {
  margin-bottom: 40px;
}

.banner-item {
  height: 100%;
  background-size: cover;
  background-position: center;
  border-radius: 8px;
  display: flex;
  align-items: center;
  position: relative;
}

.banner-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
}

.banner-content {
  position: relative;
  z-index: 1;
  color: white;
  padding: 0 40px;
  max-width: 60%;
}

.banner-content h2 {
  font-size: 28px;
  margin-bottom: 10px;
  font-weight: bold;
}

.banner-content p {
  font-size: 16px;
  margin-bottom: 20px;
  opacity: 0.9;
}

/* 分类导航样式 */
.section-title {
  text-align: center;
  margin-bottom: 30px;
  font-size: 24px;
  color: #333;
  position: relative;
  padding-bottom: 15px;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 3px;
  background-color: #ff6b6b;
}

.category-section {
  margin-bottom: 40px;
}

.category-list {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}

.category-item {
  width: 120px;
  text-align: center;
  margin-bottom: 20px;
  cursor: pointer;
  transition: transform 0.3s;
}

.category-item:hover {
  transform: translateY(-5px);
}

.category-icon {
  width: 80px;
  height: 80px;
  margin: 0 auto 10px;
  background-color: #f8f8f8;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.category-icon img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.category-name {
  font-size: 14px;
  color: #333;
}

/* 特色菜品样式 */
.featured-section {
  margin-bottom: 40px;
}

.featured-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.featured-item {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
}

.featured-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.featured-image {
  height: 200px;
  position: relative;
  overflow: hidden;
}

.featured-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}

.featured-item:hover .featured-image img {
  transform: scale(1.05);
}

.featured-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #ff6b6b;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.featured-info {
  padding: 15px;
}

.featured-tag.sold-out, .setmeal-tag.sold-out {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #909399;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

/* 如果同时有新品和售罄标签，调整位置 */
.featured-tag.sold-out {
  top: 40px; /* 当有新品标签时，售罄标签显示在下方 */
}

.featured-name {
  font-size: 18px;
  margin-bottom: 8px;
  color: #333;
}

.featured-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.featured-price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.featured-price {
  font-size: 20px;
  font-weight: bold;
  color: #ff6b6b;
}

/* 热门套餐样式 */
.setmeal-section {
  margin-bottom: 40px;
}

.setmeal-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.setmeal-card {
  cursor: pointer;
  transition: transform 0.3s;
}

.setmeal-card:hover {
  transform: translateY(-5px);
}

.setmeal-image {
  height: 180px;
  overflow: hidden;
}

.setmeal-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}

.setmeal-card:hover .setmeal-image img {
  transform: scale(1.05);
}

.setmeal-info {
  padding: 15px;
}

.setmeal-name {
  font-size: 18px;
  margin-bottom: 8px;
  color: #333;
}

.setmeal-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
  height: 40px;
  overflow: hidden;
}

.setmeal-price-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.setmeal-price {
  font-size: 20px;
  font-weight: bold;
  color: #ff6b6b;
  margin-right: 10px;
}

.setmeal-original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

/* 用户评价样式 */
.review-section {
  margin-bottom: 40px;
}

.review-item {
  display: flex;
  align-items: center;
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  height: 100%;
}

.review-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 20px;
  flex-shrink: 0;
}

.review-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.review-content {
  flex: 1;
}

.review-rating {
  margin-bottom: 10px;
}

.review-text {
  font-size: 16px;
  font-style: italic;
  color: #333;
  margin-bottom: 10px;
  line-height: 1.5;
}

.review-author {
  text-align: right;
  color: #666;
}

/* 关于我们样式 */
.about-section {
  margin-bottom: 40px;
}

.about-content {
  display: flex;
  align-items: center;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.about-image {
  flex: 1;
  height: 300px;
}

.about-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.about-text {
  flex: 1;
  padding: 30px;
}

.about-text h3 {
  font-size: 22px;
  margin-bottom: 15px;
  color: #333;
}

.about-text p {
  font-size: 15px;
  color: #666;
  margin-bottom: 15px;
  line-height: 1.6;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .featured-list {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  }
  
  .about-content {
    flex-direction: column;
  }
  
  .about-image, .about-text {
    width: 100%;
  }
  
  .banner-content {
    max-width: 80%;
  }
  
  .banner-content h2 {
    font-size: 24px;
  }
}

@media (max-width: 576px) {
  .featured-list, .setmeal-list {
    grid-template-columns: 1fr;
  }
  
  .category-item {
    width: 100px;
  }
  
  .category-icon {
    width: 70px;
    height: 70px;
  }
  
  .banner-content {
    max-width: 100%;
    padding: 0 20px;
  }
  
  .banner-content h2 {
    font-size: 20px;
  }
}
</style>